package com.hspedu.list_;

import java.util.ArrayList;
import java.util.List;

/**
 * @author DL5O
 * @version 1.0
 */
public class ListExercise01 {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new Book("红楼梦", "曹雪芹", 100));
        list.add(new Book("西游记", "吴承恩", 10));
        list.add(new Book("水浒传", "施耐庵", 19));
        list.add(new Book("三国", "罗贯中", 80));

        System.out.println("====排序前====");
        for (Object book : list) {
            System.out.println(book);
        }

        sort(list);
        System.out.println("====排序后====");
        for (Object book : list) {
            System.out.println(book);
        }
    }

    //价格要求是从小到大
    //利用list.set 实现集合元素的交换
    public static void sort(List list) {
        int listSize = list.size();
        for (int i = 0; i < listSize - 1; i++) {
            for(int j = 0 ; j < listSize - 1 - i;j++){
                Book book1 = (Book)list.get(j);//取出来后的对象是Object类型的，因此这里要向下转型
                Book book2 = (Book)list.get(j+1);

                if(book1.getPrice() > book2.getPrice()){
                    list.set(j,book2);
                    list.set(j+1,book1);
                }
            }
        }
    }
}

@SuppressWarnings("all")
class Book {
    private String name;
    private String author;
    private double price;


    public Book(String name, String author, double price) {
        this.name = name;
        this.price = price;
        this.author = author;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        String formatstr= "名称:%s\t价格:%.2f\t作者:%s\t";
        String info = String.format(formatstr,this.name,this.price,this.author);
        return info;
    }
}